<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属工厂" prop="factoryName">
        <el-input
          v-model="queryParams.factoryName"
          placeholder="请输入所属工厂"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="队列名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入队列名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['vqms:queue:area:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['vqms:queue:area:delete']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="queueAreaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属工厂" align="center" prop="factoryName" :show-overflow-tooltip="true" width="200"/>
      <el-table-column label="队列名称" align="center" prop="name" :show-overflow-tooltip="true" width="200"/>
      <el-table-column label="队列容量" align="center" prop="capacity" :show-overflow-tooltip="true" width="150"/>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <span v-if="scope.row.status === 0" style="color: red;">关闭</span>
          <span v-if="scope.row.status === 1" style="color: green;">正常</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['vqms:queue:area:update']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['vqms:queue:area:delete']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改排队队列对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12" >
            <el-form-item label="所属工厂" prop="factoryName">
              <el-autocomplete
                clearable
                style="width:100%;"
                v-model="form.factoryName"
                value-key="name"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入所属工厂"
                @select="handleSelectFactory">
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="队列名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入队列名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="队列容量" prop="capacity">
              <el-input v-model="form.capacity" placeholder="请输入队列容量" >
                <template slot="append">辆</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="form.status" placeholder="请选择状态" style="width :240px">
                <el-option v-for="status in statusList" :key="status.value" :label="status.label" :value="status.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row> 
          <el-col :span="16">
            <el-form-item label="库位" prop="locationIds">
              <el-select
                clearable
                style="width:100%;"
                v-model="form.locationIds"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请输入库位名称(可多选)"
                :remote-method="remoteMethod"
                :loading="loading">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selectFactoryList } from "@/api/vqms/factory";
import { selectStorehouseLocationList } from "@/api/vqms/storehouse";
import { listQueueArea,getQueueArea,addQueueArea,updateQueueArea,delQueueArea } from "@/api/vqms/queueArea";

export default {
  //name: "QueueArea",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排队队列表格数据
      queueAreaList: [],
      //状态
      statusList:[
        {
          label:"关闭",
          value:0
        },
        {
          label:"正常",
          value:1
        }
      ],
      // 库位下拉框
      options:[],
      // 库位集合
      locationList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        noticeTitle: undefined,
        createBy: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        factoryName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        capacity: [
          { pattern: /^(([1-9]{1}\d*)|(0{1}))?$/,message: "只能输入整数",trigger: "change"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询排队队列列表 */
    getList() {
      this.loading = true;
      listQueueArea(this.queryParams).then(response => {
        this.queueAreaList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$set(this.form, "status", 1);
      this.open = true;
      this.title = "添加排队队列";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      await getQueueArea(row.id).then(response => {
        this.form = response.data;
        this.options=response.data.locationInfo;
        //库位下拉框赋值选中
        let ids=[]
        for(let i=0;i<this.options.length;i++){
          ids.push(this.options[i].id)
        }
        this.$set(this.form, "locationIds", ids);
      });
      this.open = true;
        this.title = "修改排队队列";
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateQueueArea(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQueueArea(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids
      this.$modal.confirm('是否确认删除？').then(function() {
        return delQueueArea(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    //所属工厂异步搜索
    async querySearchAsync(queryString, cb) {
      this.factoryList=[];
      let query={
        name : queryString
      }
      await selectFactoryList(query).then(response => {
        this.factoryList = response.data
      });
      var results = queryString ? this.factoryList.filter(this.createStateFilter(queryString)) : this.factoryList;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.name.indexOf(queryString) >= 0);
      };
    },
    handleSelectFactory(item) {
      this.form.factoryName=item.name
      this.form.factoryId=item.id
    },
    //库位下拉框值改变
    async remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        let params={
          name : query
        }
        await selectStorehouseLocationList(params).then(response => {
          this.locationList = response.data
        });
        setTimeout(() => {
          this.loading = false;
          this.options = this.locationList.filter(item => {
            return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
  }
};
</script>
